/*
 * This class will be called from the ConfigurationActivity when user select particular configuration and with that config_ID
 * that configuration detail will be display. As soon as this activity started one background thread will be running which will continuously 
 * check for updated configuration also used for push notification.
 */
package com.fipl.taksar;

import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.fipl.parse.ParseConfigDetail;

public class ConfigDetailActivity extends Activity {

	private String dbName="";				// store database name
	private LinearLayout linearLayout;
	private ListView listView;				// hold list of data in the view 				
	private String args;
	private int size;						
	private Thread backgroundThread;		// this thread will be used in future when we implement push notification
	private boolean running = false;		
	private boolean handlerFlag = false;

	//Array lists which will contain data from the web after parsing config detail page.
	private ArrayList<String> iD_configdetailList = new ArrayList<String>();
	private ArrayList<String> parametroList = new ArrayList<String>();  	
	private ArrayList<String> valorList = new ArrayList<String>(); 

	private ProgressDialog progressDialog;				//define progress dialog 
	private String[] encabezadoArr; // used to convert encabezadoList array list into array which is used in the List view  
	private String[] parametroArr;	// used to convert parametroList array list into array which is used in the List View
	private String[] valorArr;		// used to convert ValorList array list into array which is used in the List View
	private MyArrayAdapter myArrayAdapter;


	@Override
	public void onCreate(Bundle savedInstanceState){
		super.onCreate(savedInstanceState);
		setContentView(R.layout.configdetail); // sets views on the screen of the device

		dbName = ((GlobalData)this.getApplicationContext()).getDbName();
		Bundle bundle = getIntent().getExtras();
		args = "fecha = '"+bundle.getString("fecha")+"'"+"and ID_config = '"+bundle.getString("id")+"'";

		/*
		 * below code is used to get screen height and width of the device.
		 */
		
		linearLayout = (LinearLayout)findViewById(R.id.middleConfigDetail);
		
		callDialog();

	}

	public void getData(){

		 // linear layout which is mapped with the linear layout in the configdetail.xml file

		listView = new ListView(this);
		listView.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
		
		ParseConfigDetail parseConfigDetail = new ParseConfigDetail(dbName,args);

		if(parseConfigDetail.ParseData(0) == 0){

			iD_configdetailList=parseConfigDetail.parseConfig.getId_configdetailArrayList();
			parametroList = parseConfigDetail.parseConfig.getParametroArrayList();
			valorList = parseConfigDetail.parseConfig.getValorArrayList();

			size = iD_configdetailList.size();
			encabezadoArr = new String[size];
			parametroArr = new String[size];
			valorArr = new String[size];

			parametroList.toArray(parametroArr);
			valorList.toArray(valorArr);
			
			// custom adapter class to set data in list view.
			myArrayAdapter = new MyArrayAdapter(this,encabezadoArr,parametroArr,valorArr);
			listView.setAdapter(myArrayAdapter);
			listView.setFocusable(true);
			listView.setBackgroundColor(Color.WHITE);
			listView.setCacheColorHint(Color.TRANSPARENT);		// used so that when listview scroll up and down it will not get black color.
			listView.setVerticalScrollBarEnabled(false);
			listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {

				public void onItemClick(AdapterView<?> arg0, View arg1, int arg2,long arg3) {
					// TODO Auto-generated method stub
					detailPage(arg2);
				}
			});

			LayoutInflater inflater = this.getLayoutInflater();
			View view = inflater.inflate(R.layout.listfooter, null, false);
			listView.addFooterView(view);
			linearLayout.addView(listView);

		}else{

			/*
			 * below dialog is called when no data is available and -1 is return from the parseconfigdetail class. 
			 */
			AlertDialog.Builder builder = new AlertDialog.Builder(ConfigDetailActivity.this);
			builder.setMessage("No Data Available!");
			builder.setPositiveButton("Ok", null);
			builder.show();
		}

	}

	public class MyArrayAdapter extends ArrayAdapter<String> {

		private final Activity context;
		private final String[] parametro;
		private final String[] valor;

		public MyArrayAdapter(Activity context, String[] encabezado, String[] parametro,String[] valor) {
			super(context, R.layout.textlist, encabezado);
			this.context=context;
			this.parametro=parametro;
			this.valor=valor;
			notifyDataSetChanged();
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			LayoutInflater inflater = context.getLayoutInflater();
			View rowView = inflater.inflate(R.layout.textlist, null, true);
			TextView equipoTextView = (TextView) rowView.findViewById(R.id.equipotxt);
			TextView fechaTextView = (TextView) rowView.findViewById(R.id.fechatxt);
			equipoTextView.setText("Parametro "+"\n"+parametro[position]);
			fechaTextView.setText("Valor "+"\n"+valor[position]);
			return rowView;
		}

	}

	Handler handler = new Handler(){
		@Override
		public void handleMessage(Message msg){
			progressDialog.dismiss();
			getData();
		}
	};

	/*
	 *  Dialog is called when activity is started.
	 *  Progress dialog is also called with it.
	 */

	public void callDialog(){

		this.progressDialog = ProgressDialog.show(ConfigDetailActivity.this,"Please wait", "Connecting.. Please wait..", true);

		new Thread(new Runnable(){
			public void run(){
				try{
					Thread.sleep(5000);
				}
				catch (Exception e){
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
				ConfigDetailActivity.this.progressDialog.dismiss();
				ConfigDetailActivity.this.handler.sendEmptyMessage(0);
			}
		}).start();
	}

	/*
	 * (non-Javadoc)
	 * @see android.app.Activity#onCreateDialog(int)
	 */

	@Override
	protected Dialog onCreateDialog(int id) {
		switch (id) {
		case 0: {

			progressDialog = new ProgressDialog(this);
			progressDialog.setMessage("Please wait while connecting...");
			progressDialog.setIndeterminate(true);
			progressDialog.setCancelable(true);
			return progressDialog;

		}
		}
		return null;
	}

	/*
	 * Below is the method which will called when user click on list view.
	 * The parameter passed in the method is index position of list view.
	 */

	public void detailPage(int listIndex){
		
	}

	@Override
	public void onDestroy(){
		super.onDestroy();
		ConfigDetailActivity.this.finish();
	}

	@Override
	protected void onStart() {
		// TODO Auto-generated method stub
		super.onStart();

		backgroundThread = new Thread(new Runnable(){
			@Override
			public void run() {
				// TODO Auto-generated method stub
				while(running){
					try {
						Thread.sleep(1000);
					} catch (InterruptedException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
				}
			}
		});
		setRunning(true);
		backgroundThread.start();
	}

	@Override
	protected void onStop() {
		// TODO Auto-generated method stub
		super.onStop();

		boolean retry = true;
		setRunning(false);

		while(retry){
			try {
				backgroundThread.join();
				retry = false;
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		ConfigDetailActivity.this.finish();
	}

	void setRunning(boolean b){
		running = b;
	}

	Handler handler2 = new Handler(){

		@Override
		public void handleMessage(Message msg) {
			// TODO Auto-generated method stub
			//			super.handleMessage(msg);
			if(handlerFlag){
				myArrayAdapter.notifyDataSetChanged();
			}
		}
	};

	
	public void GetNotificationData(){
		
	}

	@Override
	public boolean onCreateOptionsMenu (Menu menu){
		MenuInflater menuInflater = getMenuInflater();
		menuInflater.inflate(R.menu.option, menu);
		return true;
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem menuItem){

		switch (menuItem.getItemId()) {

		case R.id.menuDb:
			((GlobalData)this.getApplicationContext()).setLoginFlag(false);
			((GlobalData)this.getApplicationContext()).setMenuNo(100);
			Intent intent = new Intent();
			intent.setClass(getApplicationContext(), ConfigurationActivity.class);
			startActivity(intent);
			break;

		case R.id.menuExit:
			ConfigDetailActivity.this.finish();
			break;

		}
		return true;
	}

}
